package com.dm.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dm.cloud.api.dto.ResidentPopulation;
import com.dm.cloud.api.service.IResidentPopulationService;
import com.dm.cloud.api.vo.ResidentPopulationVo;
import com.dm.cloud.common.R;
import com.dm.cloud.dao.ResidentPopulationDao;
import com.dm.cloud.utils.sql.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ResidentPopulationServiceImpl extends ServiceImpl<ResidentPopulationDao, ResidentPopulation> implements IResidentPopulationService {

    @Override
    public R search(String id) {
        return R.data(baseMapper.selectById(id));
    }

    @Override
    public R page2(ResidentPopulationVo condition) {
        IPage<ResidentPopulation> page = new Page<>();
        page.setSize(condition.getPageSize());
        page.setCurrent(condition.getPage());

        QueryWrapper<ResidentPopulation> wrapper = new QueryWrapper();
        if(ObjectUtils.isNotNull(condition.getType())){
            wrapper.eq("type",condition.getType());
        }
        if(ObjectUtils.isNotNull(condition.getYear())){
            wrapper.eq("year",condition.getYear());
        }
        if(StringUtils.isNotBlank(condition.getCityName())){
            wrapper.like("city_name",condition.getCityName());
        }
        //列表sort排序
        SqlUtils.order(wrapper,condition);
        return R.data(this.page(page, wrapper));
    }

    @Override
    public R create(ResidentPopulationVo condition) {

        SqlUtils.valid(condition);

        ResidentPopulation ins = new ResidentPopulation();
        BeanUtils.copyProperties(condition,ins);

        //城市 年份  类型 信息保持唯一
        QueryWrapper wapper = new QueryWrapper();
        wapper.eq("city_name",ins.getCityName());
        wapper.eq("type",ins.getType());
        wapper.eq("year",ins.getYear());

        int count = baseMapper.selectCount(wapper);
        if(count>0){
            //修改已存在的行
            baseMapper.update(ins,wapper);
        }else{
            //插入行
            baseMapper.insert(ins);
        }
        return R.data("保存成功");
    }

    @Override
    public R update2(ResidentPopulationVo condition) {

        SqlUtils.valid(condition);

        ResidentPopulation ins = new ResidentPopulation();
        BeanUtils.copyProperties(condition,ins);

        QueryWrapper wapper = new QueryWrapper();
        wapper.eq("id",ins.getId());
        baseMapper.update(ins,wapper);

        return R.data("保存成功");
    }

    @Override
    public R delete(ResidentPopulationVo condition) {
        baseMapper.deleteById(condition.getId());
        return R.data("删除成功");
    }

    @Override
    public List<ResidentPopulationVo> list2(ResidentPopulationVo condition) {
        //初始化查询条件
        QueryWrapper<ResidentPopulation> wrapper = new QueryWrapper();
        if(ObjectUtils.isNotNull(condition.getType())){
            wrapper.eq("type",condition.getType());
        }
        if(ObjectUtils.isNotNull(condition.getYear())){
            wrapper.eq("year",condition.getYear());
        }
        if(StringUtils.isNotBlank(condition.getCityName())){
            wrapper.like("city_name",condition.getCityName());
        }
        //列表排序
        SqlUtils.order(wrapper,condition);
        //转换为EXCEL到处需要的实体类

        return this.list(wrapper).stream()
                .map(e -> {
                    ResidentPopulationVo tExcel = new ResidentPopulationVo();
                    BeanUtils.copyProperties(e,tExcel);
                    return tExcel;
                }).collect(Collectors.toList());
    }

    @Override
    public void importExcel(List<ResidentPopulationVo> list) {
        if(list==null || list.size()==0){
            throw new RuntimeException("导入列表为空！");
        }

        list.stream().forEach(e-> SqlUtils.valid(e));

        //清除当前表 重新导入
        LambdaUpdateWrapper<ResidentPopulation> wrapper = Wrappers.<ResidentPopulation>lambdaUpdate();
        baseMapper.delete(wrapper);
        //再批量插入 分批插入
        int size =5000;
        if(list.size()>size){
            for(int i=0;i<list.size();i+=size){
                doInsert(list,i,size);
            }
        }else{
            doInsert(list,0,list.size());
        }
    }

    /**
     * 整理集合、插入数据
     * @param list
     * @param startPos
     * @param batchSize
     */
    private void doInsert(List<ResidentPopulationVo> list, int startPos, int batchSize){
        List<ResidentPopulation> insertList = new ArrayList<>();
        //整理插入信息
        for (int j=startPos;j<Math.min(startPos+batchSize,list.size());j++) {
            ResidentPopulation insert = new ResidentPopulation();
            SqlUtils.valid(list.get(j));
            BeanUtils.copyProperties(list.get(j),insert);
            insertList.add(insert);
        }
        //批量插入
        baseMapper.batchInsert(insertList);
    }
}